
package com.xiaoma.myaudience.biz.activity;

import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.RegisterTask;
import com.xiaoma.myaudience.biz.task.SendPhonecodeTask;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;

/**
 * 用户注册页面.
 * 
 * @author st.wang
 */
public class RegisterActivity extends BaseActivity {
	
	private Context mContext;
	private LinearLayout mLoaddingLayout;
	private Button mRegisterbt;
	private Button mSendPhoneNum;
    private SendPhonecodeTask mSendPhonenumTask;
    private RegisterTask mRegisterTask;
    private ProgressDialog mSendPhoneNumProgressDialog;
    private ProgressDialog mRegisterProgressDialog;
    private Map<String,String> dataMap;
    private String phonenumber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_register);
        
        setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitle(R.string.str_register_account_pass);
        setNetEaseTitleGravity(Gravity.LEFT);
        findView();
        
        mContext = this;
        setlayoutClickListener();
        //bind the action
        
    }
    
    private void showAddInfoDialog() {
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		 dlg.show();
		 Window window = dlg.getWindow();
		 window.setContentView(R.layout.add_event_view_layout);
		 ((TextView)window.findViewById(R.id.base_title_bar_title)).setText(R.string.register_service_tiaokuan);
		 ((TextView)window.findViewById(R.id.title)).setText(R.string.register_service_tiaokuan_content);
		 window.findViewById(R.id.show_comments_back_original).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlg.dismiss();
			}
		});
	}

    /**设置组件监听动作*/
	private void setlayoutClickListener() {
		findViewById(R.id.tiaokuan).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showAddInfoDialog();
			}
		});
		
		mSendPhoneNum.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//register task
				
				EditText editPhonenum = (EditText)findViewById(R.id.edit_register_phonenum);
				String phonenum = String.format("%s",editPhonenum.getText());
				//验证
				if("".equals(phonenum.trim())){
					Tips("电话号码不能为空",Toast.LENGTH_SHORT);
					return;
				}
				phonenumber=phonenum;
				startSendPhonenumTask();
			}
		});
		mRegisterbt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dataMap = new HashMap<String, String>();
				// 用户名
				EditText editAccount = (EditText)findViewById(R.id.edit_register_account);
				String account = String.format("%s",editAccount.getText());
				//验证
				if("".equals(account.trim())){
					Tips(getResources().getString(R.string.str_user_account_is_null),Toast.LENGTH_SHORT);
					return;
				}
				dataMap.put("username", account);
				//密码
				EditText editPwd = (EditText)findViewById(R.id.edit_register_password);
				String password = String.format("%s",editPwd.getText());
				//验证
				if("".equals(password)){
					Tips(getResources().getString(R.string.str_password_is_null),Toast.LENGTH_SHORT);
					return;
				}
				dataMap.put("password", password);
				//重复密码
				EditText editRePwd = (EditText)findViewById(R.id.edit_register_repassword);
				String repassword = String.format("%s",editRePwd.getText());
				//验证
				if("".equals(repassword)){
					Tips(getResources().getString(R.string.str_password_is_null),Toast.LENGTH_SHORT);
					return;
				}else if(!repassword.equals(password)){
					Tips("两次输入密码不同",Toast.LENGTH_SHORT);
					return;
				}
				dataMap.put("password2", repassword);
				//email
				EditText editEmail = (EditText)findViewById(R.id.edit_register_email);
				String email = String.format("%s",editEmail.getText());
				//验证
				if("".equals(email)){
					Tips("email不能为空",Toast.LENGTH_SHORT);
					return;
				}
				dataMap.put("email", email);
				//手机验证码
				EditText editPhoneCode = (EditText)findViewById(R.id.edit_register_code);
				String phonecode = String.format("%s",editPhoneCode.getText());
				//验证
				if("".equals(phonecode)){
					Tips("验证码不能为空",Toast.LENGTH_SHORT);
					return;
				}
				dataMap.put("authcode", phonecode);
				
				CheckBox checked = (CheckBox) findViewById(R.id.checked_reg);
				if (!checked.isChecked()) {
					Tips("请勾选服务条款",Toast.LENGTH_SHORT);
					return;
				}
				
				startRegisterTask();
			}
		});
	};

	/**初始化组件*/
	private void findView() {
		// TODO Auto-generated method stub
		//mRegisterWebview = (WebView)findViewById(R.id.web_register_view);
		mLoaddingLayout = (LinearLayout) findViewById(R.id.lin_commen_loadding);
		mSendPhoneNum= (Button)findViewById(R.id.btn_register_getphonecode);
		mRegisterbt= (Button)findViewById(R.id.btn_register_go);
	}
	

	@Override
	public void onPreExecute(int what) {
		// TODO Auto-generated method stub
		super.onPreExecute(what);
		if(what==DataAsyncTask.TASK_ACTIVITY_SENDPHONENUM){
			if(null == mSendPhoneNumProgressDialog){
				mSendPhoneNumProgressDialog = new ProgressDialog(mContext);
				mSendPhoneNumProgressDialog.setMessage("正在发送...");
				mSendPhoneNumProgressDialog.setCancelable(true);
			}
			mSendPhoneNumProgressDialog.show();
		}
		if(what==DataAsyncTask.TASK_ACTIVITY_REGISTER){
			if(null == mRegisterProgressDialog){
				mRegisterProgressDialog = new ProgressDialog(mContext);
				mRegisterProgressDialog.setMessage("正在注册...");
				mRegisterProgressDialog.setCancelable(true);
			}
			mRegisterProgressDialog.show();
		}
	}
	
	
	@Override
	public void onPostExecute(int what, Object o) {
		// TODO Auto-generated method stub
		super.onPostExecute(what, o);
		
		if(what==DataAsyncTask.TASK_ACTIVITY_SENDPHONENUM){
			if(null != mSendPhoneNumProgressDialog)
				mSendPhoneNumProgressDialog.dismiss();
			//取出
			String  code = (String)o;
			String tips = "";
			if(code!=null){
				if(code.equals("0")){
					tips="发送成功";
					//验证码输入框置为可用
					//findViewById(R.id.edit_register_code).setEnabled(true);
				}else if(code.equals("-1")){
					tips="手机号不正确";
				}else if(code.equals("2")){	
					tips = "发送失败，请稍后再试";
				}

			}
			Tips(tips);
			
		}
		if(what==DataAsyncTask.TASK_ACTIVITY_REGISTER){
			if(null != mRegisterProgressDialog)
				mRegisterProgressDialog.dismiss();
			//取出
			String  code = (String)o;
			if(code!=null){
				int intcode =Integer.valueOf(code);
				String tips = "";
				switch (intcode) {
				case 0:
					tips="注册成功,返回登录";
					Intent intent = new Intent(mContext, LoginActivity.class);
					startActivity(intent);
					break;
				case -1:
					tips="验证码不正确";
					break;
				case -2:
					tips="账户名不合法";
					break;
				case -3:
					tips="密码不合法";
					break;
				case -4:
					tips="两次输入的密码不一致";
					break;
				case -5:
					tips="邮箱格式不正确";
					break;
				case -6:
					tips="账户名已经注册过了";
					break;
				case -7:
					tips="邮箱已经注册过了";
					break;
				default:
					break;
			}
			Tips(tips);
			}
		}
	}

	
	/**启动发送短信任务*/
	private void startSendPhonenumTask() {
		cancelSendPhonenumTask();
		mSendPhonenumTask = new SendPhonecodeTask(mContext,
				DataAsyncTask.TASK_ACTIVITY_SENDPHONENUM, this);
		mSendPhonenumTask.execute(phonenumber);
	}

	/**关闭发送短信任务*/
	private void cancelSendPhonenumTask() {
		if (mSendPhonenumTask != null) {
			mSendPhonenumTask.cancel(true, true);
		}
		mSendPhonenumTask = null;
	}
	
	/**启动注册任务*/
	private void startRegisterTask() {
		cancelRegisterTask();
		mRegisterTask = new RegisterTask(mContext,
				DataAsyncTask.TASK_ACTIVITY_REGISTER, this);
		//取数据
		mRegisterTask.execute(dataMap);
	}

	/**关闭注册任务*/
	private void cancelRegisterTask() {
		if (mRegisterTask != null) {
			mRegisterTask.cancel(true, true);
		}
		mRegisterTask = null;
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		cancelSendPhonenumTask();
	}
	
	private String parseURL(String url,String key){
	    
		String rstult = "";
		
		if(null==key || "".equalsIgnoreCase(key)){
	       
		}else{
	        
			int i = url.indexOf("?");
			if(i <= url.length() - 1){
				String param =  url.substring(i+1,url.length());
				String[] values =  param.split("&");
				if(null!=values){
					for(int index=0;index<values.length;index++){
						if(values[index].contains(key)){
							String[] keys = values[index].split("=");
							if(keys.length>1){
								rstult = keys[1];
								break;
							}
						}
					}
				}
			}
		}
		
	    return rstult;
	}
}
